package com.company.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.project.common.config.WebsocketService;
import com.company.project.common.exception.BusinessException;
import com.company.project.common.utils.Constant;
import com.company.project.common.utils.DateUtils;
import com.company.project.entity.BusiUrgentEntity;
import com.company.project.entity.SysDept;
import com.company.project.entity.SysUser;
import com.company.project.mapper.BusiUrgentMapper;
import com.company.project.service.BusiUrgentService;
import com.company.project.service.DeptService;
import com.company.project.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


@Service("busiUrgentService")
public class BusiUrgentServiceImpl extends ServiceImpl<BusiUrgentMapper, BusiUrgentEntity> implements BusiUrgentService {

    @Resource
    private UserService userService;
    @Resource
    private DeptService deptService;
    @Resource
    private WebsocketService websocketService;
    @Override
    public void wholeAdd(BusiUrgentEntity busiUrgentEntity) throws BusinessException {
        // 查询当前用户ID
        String userId = busiUrgentEntity.getUserId();
        // 查询当前用户所属部门名称
        SysUser user = userService.getById(userId);
        String deptId = user.getDeptId();
        busiUrgentEntity.setName(user.getRealName());
        SysDept sysDept = deptService.getById(deptId);
        String detpName = sysDept.getName();
        busiUrgentEntity.setDetp(detpName);
        String now = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN);
        busiUrgentEntity.setCreateTime(now);
        busiUrgentEntity.setUpdateTime(now);

        // 查看用户是否在线
        boolean online = WebsocketService.online(userId);
        if (online) {
            // 发送通知给用户
            websocketService.sendMessage(JSON.toJSONString(busiUrgentEntity), userId);
        }

        this.save(busiUrgentEntity);
    }

    @Override
    public void wholeDeal(BusiUrgentEntity busiUrgentEntity) throws BusinessException {
        String now = DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN);
        busiUrgentEntity.setDealStatus(Constant.DEAL);
        busiUrgentEntity.setUpdateTime(now);
        updateById(busiUrgentEntity);
    }

}